package whisper.api.gateway.frame.auth.repository;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import whisper.api.gateway.frame.auth.config.DbConfig;
import whisper.api.gateway.frame.auth.domain.Permission;
import whisper.api.gateway.frame.auth.domain.Role;

import java.util.List;

/**
 * Created by JT on 2017/9/25.
 */
@Repository
public class PermissionRepositoryImpl implements PermissionRepository {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void insertPermission(Permission permission) {
        String[] columnArr = (String[]) ArrayUtils.remove(DbConfig.TABLE_COLUMNS_PERMISSION, 0);
        String columns = String.join(",", columnArr);
        String sql = String.format("INSERT INTO %s(%s) VALUES(?, ?, ?, ?, ?)",
                DbConfig.TABLE_NAME_PERMISSION, columns);
        Object[] params = new Object[]{
                permission.getName(), permission.getUrl(), permission.getType(),
                permission.getParentId(), permission.getSort()
        };
        jdbcTemplate.update(sql, params);
    }

    @Override
    public void addPermissionsToRole(Integer pid, Integer rid) {
        String columns = String.join(",", DbConfig.TABLE_COLUMNS_ROLE_PERMISSION);
        String sql = String.format("INSERT INTO %s(%s) VALUES(?, ?)",
                DbConfig.TABLE_NAME_ROLE_PERMISSION, columns);
        Object[] params = new Object[] {rid, pid};
        jdbcTemplate.update(sql, params);
    }

    /**
     * 通过资源URL查询拥有该权限的角色
     *
     * @param url ：请求地址
     * @return
     */
    @Override
    public List<Role> findRolesByPermissioinUrl(String url) {
        String sql = String.format("SELECT R.ID AS ID, R.CODE AS CODE, R.NAME AS NAME FROM %s AS P, %s AS RP, %s AS R WHERE P.URL=? AND RP.PID=P.ID AND R.ID=RP.RID",
                DbConfig.TABLE_NAME_PERMISSION, DbConfig.TABLE_NAME_ROLE_PERMISSION, DbConfig.TABLE_NAME_ROLE);
        Object[] params = new Object[]{url};
        return jdbcTemplate.query(sql, params, new BeanPropertyRowMapper<>(Role.class));
    }

    /**
     * 通过资源URL与请求类型 查询拥有该权限的角色
     *
     * @param url  ：资源URL
     * @param type ：请求类型： GET、POST、PUT、DELETE
     * @return
     */
    @Override
    public List<Role> findRolesByPermissionUrlAndType(String url, String type) {
        String sql = String.format("SELECT R.ID AS ID, R.CODE AS CODE, R.NAME AS NAME FROM %s AS P, %s AS RP, %s AS R WHERE P.URL=? AND TYPE=? AND RP.PID=P.ID AND R.ID=RP.RID",
                DbConfig.TABLE_NAME_PERMISSION, DbConfig.TABLE_NAME_ROLE_PERMISSION, DbConfig.TABLE_NAME_ROLE);
        Object[] params = new Object[]{url, type};
        return jdbcTemplate.query(sql, params, new BeanPropertyRowMapper<>(Role.class));
    }


}
